/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useRef, useCallback, useEffect, useMemo } from 'react';
import ProForm, { ProFormSelect, ProFormText } from '@ant-design/pro-form';
import ProCard from '@ant-design/pro-card';
import { Row, Col, DatePicker, Form, Input } from 'antd';
import { initialValues, initialFormValues } from './utils';
import { getQueryConfig } from '@/services/tools/qjOrder';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { Moment } from 'moment';
import moment from 'moment';
import { isArray } from 'lodash';
import KbAddressSelect from '@/components/KbAddressSelect';

const { RangePicker } = DatePicker;
const { TextArea } = Input;
const idRegExr = /[\r\n\;\,]/g;

const textAreaSize = {
  minRows: 5,
  maxRows: 20,
};
const rules = [{ pattern: /^1\d{10}$/, message: '手机号格式错误' }];
interface FormProps {
  onChange?: Function;
  onSubmit: Function;
}
interface SelectParamsType {
  order_status: string[];
  brand: Record<string, string>;
  pay_method: Record<string, string>;
}

const OrderFrom: React.FC<FormProps> = (props) => {
  const { onSubmit } = props;
  const [sendAdd, setSendAdd] = useState<any[]>([]);
  const [receiveAdd, setReceiveAdd] = useState<any[]>([]);
  const formRef = useRef<ProFormInstance>();
  const [tValue, settValue] = useState<string>('');
  const [currentDate, setDate] = useState<[Moment, Moment]>();
  const [selectParams, setselectParams] = useState<SelectParamsType>();

  const selectParamsMo = useMemo(() => {
    const obj = {
      order_status: [],
      brand: [],
      pay_method: [],
    };
    if (selectParams) {
      Object.keys(selectParams).map((item) => {
        const response = selectParams[item];
        obj[item] = isArray(response)
          ? response.map((label, value) => ({
              label,
              value,
            }))
          : Object.keys(response).map((key) => ({
              value: key,
              label: response[key],
            }));
      });
    }
    return obj;
  }, [selectParams]);

  useEffect(() => {
    getQueryConfig().then((res) => {
      const { data, success } = res;
      if (success) {
        setselectParams(data);
        return data;
      }
    });
  }, []);

  const handleFinish = async (values: any) => {
    const { date, waybill_no, send_address, receive_address, ...rest } = values;
    const formatparams: any = {};
    if (date) {
      formatparams.start_time = moment(date[0]).format('YYYY-MM-DD');
      formatparams.end_time = moment(date[1]).format('YYYY-MM-DD');
      delete values.date;
    }
    if (waybill_no) {
      formatparams.waybill_no = waybill_no
        .replace(idRegExr, ',')
        ?.split(',')
        .filter((i: string) => !!i);
    }

    if (send_address) {
      const add: string[] = sendAdd?.map((item) => item.label);
      formatparams.shipper_province = add[0];
      formatparams.shipper_city = add[1];
      formatparams.shipper_county = add[2];
    }
    if (receive_address) {
      const add: string[] = receiveAdd?.map((item) => item.label);
      formatparams.shipping_province = add[0];
      formatparams.shipping_city = add[1];
      formatparams.shipping_county = add[2];
    }
    onSubmit({
      ...rest,
      ...formatparams,
    });
  };
  const handleCalendarChange = (date: any) => {
    setDate(date);
  };
  const handleDisabledDate = useCallback(
    (current: any) => {
      const [y, m, d] = moment(current).format('YYYY-MM-DD').split('-');
      const [ny, nm, nd] = moment().format('YYYY-MM-DD').split('-');
      if (
        parseInt(ny) < parseInt(y) ||
        (nm <= m && ny <= y && parseInt(nd) < parseInt(d)) ||
        (nm < m && ny <= y)
      ) {
        return true;
      }
      if (currentDate) {
        const selectedDate = currentDate[0] || currentDate[1];
        const currentD = Math.abs(moment(current).diff(moment(selectedDate), 'day'));
        const disabled = currentD > 31;
        return disabled;
      }
      return false;
    },
    [currentDate],
  );
  return (
    <ProCard>
      <ProForm
        layout='horizontal'
        submitter={{
          resetButtonProps: {
            style: { marginLeft: 100 },
          },
        }}
        initialValues={initialValues}
        onFinish={handleFinish}
        formRef={formRef}
      >
        <Row justify='space-between'>
          <Col xs={24} sm={24} md={16} lg={16} xl={16}>
            <Row justify='space-around' gutter={2}>
              <Col md={10} xl={10} xs={24} sm={24}>
                <ProForm.Item
                  name='date'
                  label='下单时间'
                  initialValue={initialFormValues.datePicker}
                >
                  <RangePicker
                    format='YYYY-MM-DD'
                    disabledDate={handleDisabledDate}
                    onCalendarChange={handleCalendarChange}
                  />
                </ProForm.Item>
                <ProFormText
                  label='收件人手机号'
                  name='shipping_mobile'
                  rules={rules}
                  placeholder='请输入收件人手机号'
                />
                <ProFormText
                  label='用户手机号'
                  name='user_mobile'
                  rules={rules}
                  placeholder='请输入（团长/团员）'
                />

                <ProFormSelect name='brand' label='下单品牌' options={selectParamsMo.brand} />
                <ProForm.Item label='寄件地址' name={'send_address'}>
                  <KbAddressSelect
                    level={2}
                    placeholder='请选择省市区/县'
                    onChange={(_, optin) => setSendAdd(optin)}
                  />
                </ProForm.Item>
              </Col>
              <Col md={10} xl={10} xs={24} sm={24}>
                <ProFormText
                  label='寄件人手机号'
                  name='shipper_mobile'
                  rules={rules}
                  placeholder='请输入寄件人手机号'
                />
                <ProFormSelect
                  label='订单状态'
                  name='order_status'
                  options={selectParamsMo.order_status}
                />
                <ProFormText label='交易流水号' name='trade_number' />
                <ProFormSelect
                  name='pay_method'
                  label='付款方式'
                  options={selectParamsMo.pay_method}
                />
                <ProForm.Item label='收件地址' name={'receive_address'}>
                  <KbAddressSelect
                    level={2}
                    placeholder='请选择省市区/县'
                    onChange={(_, optin) => setReceiveAdd(optin)}
                  />
                </ProForm.Item>
              </Col>
            </Row>
          </Col>
          <Col xs={24} sm={24} md={8} lg={8} xl={8}>
            <Form.Item
              label='运单号'
              name='waybill_no'
              hasFeedback
              normalize={(value) => {
                const ids: string[] = value.replace(idRegExr, ',')?.split(',');
                const len = ids.join().split(',').length;
                if (len > 20) {
                  return tValue;
                }
                settValue(value);
                return value;
              }}
            >
              <TextArea showCount autoSize={textAreaSize} />
            </Form.Item>
          </Col>
        </Row>
      </ProForm>
    </ProCard>
  );
};
export default OrderFrom;
